#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <curl/curl.h>
#include <cjson/cJSON.h>

#define API_URL "https://v2.jinrishici.com/info"
#define API_KEY "xXlijSFfUGk6K/fqgJkG6H5Al47ICDGJ"

// 打印推荐的古诗词
void print_recommended_poetry(const char *response, size_t size) {
    // 解析 JSON 响应
    cJSON *json = cJSON_ParseWithLength(response, size);
    if (json == NULL) {
        fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    // 获取 "data" 对象
    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    if (!cJSON_IsObject(data)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'data' 对象\n");
        cJSON_Delete(json);
        return;
    }

    // 获取 "content" 字符串
    cJSON *content = cJSON_GetObjectItemCaseSensitive(data, "content");
    if (!cJSON_IsString(content) || (content->valuestring == NULL)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'content' 字符串\n");
        cJSON_Delete(json);
        return;
    }

    // 打印推荐的古诗词
    printf("推荐的古诗词：%s\n", content->valuestring);

    // 释放 JSON 对象
    cJSON_Delete(json);
}

// 用于存储响应数据的结构体
struct MemoryStruct {
    char *memory;
    size_t size;
};

// 回调函数，用于将响应数据写入内存
static size_t WriteMemoryCallback(void *contents, size_t size, size_t nmemb, void *userp) {
    size_t realsize = size * nmemb;
    struct MemoryStruct *mem = (struct MemoryStruct *)userp;

    char *ptr = realloc(mem->memory, mem->size + realsize + 1);
    if (ptr == NULL) {
        // 内存不足
        fprintf(stderr, "Not enough memory (realloc returned NULL)\n");
        return 0;
    }

    mem->memory = ptr;
    memcpy(&(mem->memory[mem->size]), contents, realsize);
    mem->size += realsize;
    mem->memory[mem->size] = 0;

    return realsize;
}

// 打印API返回的天气情况
void print_weather_info(const char *response) {
    // 解析 JSON 响应
    cJSON *json = cJSON_Parse(response);
    if (json == NULL) {
        fprintf(stderr, "解析 JSON 失败: [%s]\n", cJSON_GetErrorPtr());
        return;
    }

    // 获取 "data" 对象
    cJSON *data = cJSON_GetObjectItemCaseSensitive(json, "data");
    if (!cJSON_IsObject(data)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'data' 对象\n");
        cJSON_Delete(json);
        return;
    }

    // 获取区域信息
    cJSON *region = cJSON_GetObjectItemCaseSensitive(data, "region");
    if (!cJSON_IsString(region) || (region->valuestring == NULL)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'region' 字符串\n");
        cJSON_Delete(json);
        return;
    }

    // 获取天气数据
    cJSON *weatherData = cJSON_GetObjectItemCaseSensitive(data, "weatherData");
    if (!cJSON_IsObject(weatherData)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'weatherData' 对象\n");
        cJSON_Delete(json);
        return;
    }

    // 获取天气相关信息
    cJSON *temperature = cJSON_GetObjectItemCaseSensitive(weatherData, "temperature");
    cJSON *windDirection = cJSON_GetObjectItemCaseSensitive(weatherData, "windDirection");
    cJSON *windPower = cJSON_GetObjectItemCaseSensitive(weatherData, "windPower");
    cJSON *weather = cJSON_GetObjectItemCaseSensitive(weatherData, "weather");
    cJSON *humidity = cJSON_GetObjectItemCaseSensitive(weatherData, "humidity");

    if (!cJSON_IsNumber(temperature) || !cJSON_IsString(windDirection) || 
        !cJSON_IsNumber(windPower) || !cJSON_IsString(weather) || 
        !cJSON_IsNumber(humidity)) {
        fprintf(stderr, "JSON 格式错误: 找不到 'temperature'、'windDirection'、'windPower'、'weather' 或 'humidity' 字段\n");
        cJSON_Delete(json);
        return;
    }

    // 打印天气情况
    printf("区域：%s\n", region->valuestring);
    printf("天气情况：%s\n", weather->valuestring);
    printf("温度：%.1f 摄氏度\n", cJSON_GetNumberValue(temperature));
    printf("风向：%s\n", windDirection->valuestring);
    printf("风力：%d\n", cJSON_GetNumberValue(windPower));
    printf("湿度：%.1f%%\n", cJSON_GetNumberValue(humidity));

    // 释放 JSON 对象
    cJSON_Delete(json);
}

int main(void) {
    CURL *curl;
    CURLcode res;
    struct MemoryStruct chunk;
    CURL *client;
     CURLcode err;
    char *response;
    size_t size;

    chunk.memory = malloc(1);  // 初始内存分配
    chunk.size = 0;            // 初始大小为 0

  // 创建内存流
    FILE *memstream = open_memstream(&response, &size);
    if (memstream == NULL) {
        perror("open_memstream");
        return 1;
    }

    // 初始化 CURL
    curl_global_init(CURL_GLOBAL_ALL);
    client = curl_easy_init();

    // 设置 CURL 选项
    curl_easy_setopt(client, CURLOPT_URL, "https://v2.jinrishici.com/sentence");
    curl_easy_setopt(client, CURLOPT_WRITEDATA, memstream);

    struct curl_slist *headers = NULL;
    headers = curl_slist_append(headers, "X-User-Token: o9M10gtneoIxRLk5UO13fUG7guYxnS7h"); // 替换 YOUR_API_KEY 为你的 API Key
    curl_easy_setopt(client, CURLOPT_HTTPHEADER, headers);

    // 执行 CURL 请求
    err = curl_easy_perform(client);
    fclose(memstream); // 关闭内存流

    if (err != CURLE_OK) {
        fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(err));
    } else {
        // 打印推荐的古诗词
        print_recommended_poetry(response, size);
    }


    // 初始化 CURL
    curl_global_init(CURL_GLOBAL_ALL);
    curl = curl_easy_init();
    if (curl) {
        // 设置 CURL 选项
        curl_easy_setopt(curl, CURLOPT_URL, API_URL);
        curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteMemoryCallback);
        curl_easy_setopt(curl, CURLOPT_WRITEDATA, (void *)&chunk);

        struct curl_slist *headers = NULL;
        headers = curl_slist_append(headers, "Content-Type: application/json");
        headers = curl_slist_append(headers, "X-User-Token: " API_KEY);
        curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);

        // 执行 CURL 请求
        res = curl_easy_perform(curl);
        if (res != CURLE_OK) {
            fprintf(stderr, "curl_easy_perform() 失败: %s\n", curl_easy_strerror(res));
        } else {
            // 解析并打印天气情况
            print_weather_info(chunk.memory);
        }

        // 清理资源
        curl_slist_free_all(headers);
        curl_easy_cleanup(curl);
        free(chunk.memory);
    }

    // 全局清理
    curl_global_cleanup();

    return 0;
}